package com.atguigu.gmall.realtime.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程池工具类
 * <p>
 * 双重锁问题解决方案参考：https://blog.csdn.net/u013490280/article/details/108722926
 * <p>
 * 双重锁与单例模式：https://blog.csdn.net/zhangzeyuaaa/article/details/42673245
 *
 * @author lvbingbing
 * @date 2022-06-28 16:06
 */
@Slf4j
public class ThreadPoolUtils {

    private volatile static ThreadPoolExecutor threadPoolExecutor;

    public static ThreadPoolExecutor getInstance() {
        if (threadPoolExecutor == null) {
            synchronized (ThreadPoolExecutor.class) {
                if (threadPoolExecutor == null) {
                    log.info("创建线程池。");
                    int corePoolSize = 4;
                    int maximumPoolSize = 20;
                    long keepAliveTime = 300;
                    TimeUnit unit = TimeUnit.SECONDS;
                    BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(Integer.MAX_VALUE);
                    threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
                }
            }
        }
        return threadPoolExecutor;
    }
}